package com.huaxin.hxmodulesystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huaxin.hxmodulesystem.dto.ResponseCode;
import com.huaxin.hxmodulesystem.dto.ResponseResult;
import com.huaxin.hxmodulesystem.mapper.OrganizationMapper;
import com.huaxin.hxmodulesystem.mapper.RolePermissionMapper;
import com.huaxin.hxmodulesystem.models.Organization;
import com.huaxin.hxmodulesystem.models.Permission;
import com.huaxin.hxmodulesystem.models.RolePermission;
import com.huaxin.hxmodulesystem.service.RolePermissionService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class RolePermissionServiceImpl extends ServiceImpl<RolePermissionMapper, RolePermission> implements RolePermissionService {
    private final CacheManager cacheManager;

    private final ObjectMapper objectMapper = new ObjectMapper();

    private final ApplicationContext applicationContext;

    private final OrganizationMapper organizationMapper;

    /**
     * 添加权限与角色的关系
     *
     * @param permissionId 权限ID
     * @param roleId       角色ID
     * @return
     */
    @Override
    public ResponseResult<String> addPermissionRole(String permissionId, String roleId) {
        if (StringUtils.isBlank(permissionId)) {
            return ResponseResult.parameterError(null, "权限ID不能为空");
        }
        if (StringUtils.isBlank(roleId)) {
            return ResponseResult.parameterError(null, "角色ID不能为空");
        }
        RolePermission rolePermission = new RolePermission();
        rolePermission.setPermissionId(permissionId);
        rolePermission.setRoleId(roleId);
        if (this.save(rolePermission)) {
            return ResponseResult.ok(null);
        } else {
            return ResponseResult.failure(ResponseCode.INTERNAL_ERROR, "添加权限与角色关系失败，请稍后再试！", null);
        }
    }

    /**
     * 删除权限与角色的关系
     *
     * @param permissionId 权限ID
     * @param roleId       角色ID
     * @return
     */
    @Override
    @CacheEvict(value = "rolePermissionList", key = "#roleId")
    public Boolean deletePermissionRole(String permissionId, String roleId) {
        if (StringUtils.isBlank(permissionId)) {
            return false;
        }
        if (StringUtils.isBlank(roleId)) {
            return false;
        }
        QueryWrapper<RolePermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("permission_id", permissionId);
        queryWrapper.eq("role_id", roleId);
        return this.remove(queryWrapper);
    }

    /**
     * 根据角色id，查询权限列表
     *
     * @param roleId 角色ID
     * @return
     */
    @Override
    @Cacheable(value = "rolePermissionList", key = "#roleId", unless = "#result == null")
    public List<Permission> queryPermissionListByRoleId(String roleId, Integer userType, String orgId) {
        if (StringUtils.isBlank(roleId)) {
            return null;
        }
        if (userType == null || userType <= 0) {
            return null;
        }
        //如果是企业用户，那就要查看该企业是否已经审核通过了
        if (userType == 2) {
            Organization organization = organizationMapper.selectById(orgId);
            if (organization == null) {
                return this.baseMapper.queryPermissionListByRoleAndUserType(roleId, 2, 0);
            }
            return this.baseMapper.queryPermissionListByRoleAndUserType(roleId, userType, organization.getStatus());
        } else {
            return this.baseMapper.queryPermissionListByRoleAndUserType(roleId, userType, 0);
        }
    }

    /**
     * 根据角色id，查询权限列表
     *
     * @param pageNum  页码
     * @param pageSize 页大小
     * @param roleId   角色ID
     * @return
     */
    @Override
    public ResponseResult<Page<Permission>> queryPermissionListByRole(Integer pageNum, Integer pageSize, String roleId) {
        if (StringUtils.isBlank(roleId)) {
            return ResponseResult.parameterError(null, "角色ID不能为空");
        }
        Page<Permission> page = new Page<>(pageNum, pageSize);
        return ResponseResult.ok(this.baseMapper.queryPermissionListByRole(page, roleId));
    }
}